package com.yoi.SendAndRecv;


import com.yoi.bean.Constants;
import com.yoi.mapper.BrokerMessageLogMapper;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
/**
 * Version2
 */
@Component
public class OrderSender {


    @Resource(name="FirstRabbitTemplate")
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BrokerMessageLogMapper brokerMessageLogMapper;
    //回调函数：confirm确认
    final RabbitTemplate.ConfirmCallback confirmCallback=new RabbitTemplate.ConfirmCallback(){
         @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationDate:"+correlationData);
            String messageId=correlationData.getId();
            if(ack){
                brokerMessageLogMapper.changeBrokerMessageLogStatus(messageId,Constants.ORDER_SEND_SUCCESS);

            }else{
                System.out.println("异常处理");
            }
        }
    };

    //发送消息方法调用，构建自定义对象消息
    //生产者1
    public void send(Object object) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(new Date().toString());
        System.out.println("----我要买书，我的身份是生产者1，发出购书信息为----" + object.toString() + "----");
        rabbitTemplate.convertAndSend("rabbitmq1-resource1-exchange", "rabbitmq.rabbitmq1.resource1.base", object, correlationData);
    }

    //发送对象为Json字符串
    public void sendJsonMessage(Object object){
        rabbitTemplate.setConfirmCallback(confirmCallback);
        CorrelationData correlationData=new CorrelationData();
        correlationData.setId(new Date().toString());
        rabbitTemplate.convertAndSend("order-exchange","order.abcd",object,correlationData);
    }


}
